package acptTests;


import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import junit.framework.TestCase;

import msgParser.Strings;

import org.junit.Before;

import protocol.AsyncServerProtocol;
import protocol.ForumProtocol;
import protocol.ServerProtocolFactory;
import reactor.ConnectionHandler;
import reactor.ReactorData;


import tokenizer.FixedSeparatorMessageTokenizer;
import tokenizer.MessageTokenizer;
import tokenizer.StringMessage;
import tokenizer.TokenizerFactory;

public class ServerTest extends TestCase 
{
	protected protocol.AsyncServerProtocol<StringMessage> sp;
	protected ConnectionHandler ch;
	
	
	@Before
	public void setUp() {
		TreeMap<String, String> conn_data = new TreeMap<String, String>();
		sp = new ForumProtocol(conn_data);
		
		SocketChannel sc = null;
		try {sc = SocketChannel.open();} 
		catch (IOException e) {
			System.out.println("Unable to initialize SocketChannel");
		}
		
		ExecutorService executor = Executors.newFixedThreadPool(1);
		Selector selector = null;
		
		ServerProtocolFactory<StringMessage> protocolMaker = new ServerProtocolFactory<StringMessage>() {
			public AsyncServerProtocol<StringMessage> create(TreeMap<String, String> connectionRecord) {
				return new ForumProtocol(connectionRecord);
			}
		};
		ServerProtocolFactory spf = protocolMaker;
				
		final Charset charset = Charset.forName("UTF-8");
		TokenizerFactory<StringMessage> tokenizerMaker = new TokenizerFactory<StringMessage>() {
			public MessageTokenizer<StringMessage> create() {
				return new FixedSeparatorMessageTokenizer("\n", charset);
			}
		};
		TokenizerFactory tf = tokenizerMaker;
		ReactorData dt = new ReactorData(executor, selector, spf, tf);
		ch = new ConnectionHandler(sc, dt, null);
		
	}
	
	public String getWord(String str, int idx){
		String[] arr = str.split(Strings.DELIMITER);
		if (idx >=arr.length)
			return null;
		return arr[idx];
	}
}
